package com.swm.julie.rest.crud.twitt.update;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swm.julie.rest.crud.twitt.TwittDocFormat;
import com.swm.julie.rest.crud.twitt.search.SearchTwitt;

public class UpdateTwittServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		SearchTwitt search = new SearchTwitt();
		search.setIndexDir(System.getProperty("user.dir") + "/tempNewTwitt");
		TwittDocFormat twitt = search.search(Long.valueOf(req.getParameter("id")));
		req.setAttribute("twitt", twitt);

		//Dispatch to the view page
		System.out.println("UpdateTwittServlet.doGet() : Dispatch to updateForm.jsp");
		RequestDispatcher agent = req.getRequestDispatcher("updateForm.jsp");
		agent.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		req.setCharacterEncoding("UTF-8");
		
		//get old twitt
//		TwittDocFormat oldTwitt = (TwittDocFormat) req.getAttribute("twitt");
		TwittDocFormat oldTwitt = new TwittDocFormat();
		oldTwitt.setId(Long.valueOf(req.getParameter("id")));
		oldTwitt.setPostdate(req.getParameter("oldpostdate"));
		oldTwitt.setContents(req.getParameter("oldcontents"));
		oldTwitt.setLinkInfo(req.getParameter("oldlinkInfo"));
		oldTwitt.setPostUrl(req.getParameter("oldposturl"));


		//get new twitt
		TwittDocFormat newTwitt = new TwittDocFormat();
		newTwitt.setId(Long.valueOf(req.getParameter("id")));
		newTwitt.setPostdate(req.getParameter("newpostdate"));
		newTwitt.setContents(req.getParameter("newcontents"));
		newTwitt.setLinkInfo(req.getParameter("newlinkInfo"));
		newTwitt.setPostUrl(req.getParameter("newposturl"));

		UpdateTwitt update = new UpdateTwitt();
		update.setIndexDir("D:\\tempNewTwitt");
		update.update(newTwitt);

		//set attributes
		req.removeAttribute("twitt");
		req.setAttribute("oldTwitt", oldTwitt);
		req.setAttribute("newTwitt", newTwitt);

		//Dispatch to the view page
		System.out.println("UpdateTwittServlet.doPost() : Dispatch to updateResult.jsp");
		RequestDispatcher view = req.getRequestDispatcher("updateResult.jsp");
		view.forward(req, resp);

	}
}
